package cc.rengu.redp.bizimpl.upmp.controller;


import cc.rengu.igas.bomp.facade.BompMchntManageService;
import cc.rengu.igas.bomp.facade.request.ImageFileUpDownloadRequest;
import cc.rengu.igas.bomp.facade.response.ImageFileUpDownloadResponse;
import cc.rengu.redp.bizimpl.enums.*;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.domain.*;
import cc.rengu.redp.bizimpl.upmp.service.*;
import cc.rengu.redp.bizimpl.upmp.vo.DirectMchntImageManageVO;
import cc.rengu.redp.bizimpl.upmp.vo.ImageInfoVO;
import cc.rengu.redp.bizimpl.upmp.vo.OperationResult;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.DateUtils;
import cc.rengu.redp.bizimpl.utils.GZIPUtils;
import cc.rengu.redp.common.controller.BaseController;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.crypto.hash.Hash;
import org.joda.time.ReadableDateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author 刘玉亮.LL
 */
@Slf4j
@Api(tags = "商户管理:直连商户管理")
@RestController
@RequestMapping(value = "/admin/mer/directBaseInfo")
public class DirectMchntBaseInfoController extends BaseController {

    private long oprMenuId = 1;
    private String oprMenuName = "商户管理:银联直连商户管理";
    private long chkMenuId = 2;
    private String chkMenuName = "商户管理:银联直连商户管理";
    private String webNextUrl = "/admin/mer/directBaseInfo/edit-tabs";
    @Autowired
    private IUpmpSysParamService upmpSysParamService;
    @Autowired
    private IDirectMchntBaseInfoService directBaseInfoService;

    @Autowired
    private IDirectMchntSignInfoService directSignInfoService;

    @Autowired
    private IDirectMchntClearInfoService directClearInfoService;

    @Autowired
    private IDirectMchntBizInfoService directMchntBizInfoService;

    @Autowired
    private IDirectMchntImageInfoService directMchntImageInfoService;
    @Autowired
    private RegionInfoService regionInfoService;
    @Autowired
    private IUpmpPrivilegeCheckService privilegeCheckService;
    @Autowired
    private IBizTmpService bizTmpService;
    @Autowired
    private IBizHisService bizHisService;
    @Autowired
    private AreaInfoService areaInfoService;

    @Autowired
    private IndustryInfoService industryInfoService;

    @Autowired
    private MerGrpInfoService merGrpInfoService;

    @Autowired
    private IUpmpBMchntBaseInfoService bMchntBaseInfoService;

    @DubboReference(version = "${dubbo.protocol.version}", check = false)
    private BompMchntManageService bompMchntManageService;


    @RequiresPermissions("商户管理:间联商户管理:商户基本信息")
    @GetMapping(value = "/listHis")

    public Map<String, Object> findHisByPage(QueryRequest request, BizHis entity) {
        return getDataTable(this.bizHisService.findByPage(request, entity));
    }

    //@RequiresPermissions("商户管理:银联直连商户管理")
    @GetMapping(value = "/list")

    public Map<String, Object> findHisByPage(QueryRequest request, DirectMchntBaseInfo entity) {
        return getDataTable(this.directBaseInfoService.findByPage(request, entity));
    }


    // tab页面跳转 逻辑
    @GetMapping(value = "/edit-tabs")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "主键", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "操作标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String")
    })
    public Map editTabs(@NotBlank(message = "{required}") String id, @NotBlank(message = "{required}") String optFlag, @NotBlank(message = "{required}") String instId) {
        Map<String, Object> result = new HashMap<>();
        if ("upd".equals(optFlag) || "chk".equals(optFlag) || "view".equals(optFlag) || "stop".equals(optFlag) ||
                "use".equals(optFlag) || "cancel".equals(optFlag) || "viewR".equals(optFlag)) {
            // 获取商户基本信息
            DirectMchntBaseInfo merbase = directBaseInfoService.getById(id);

            result.put("id", merbase.getId());
            result.put("mchntCd", merbase.getMchntCd());
            // 处理新增界面中途关闭，获取上一次数据的状态，修改时如果上一次是新增状态，还是按照新增状态
            result.put("lastAuditStatus", merbase.getAuditStatus());
        }
        result.put("optFlag", optFlag);
        result.put("instId", instId);
        return result;
    }

    // -----------------------------------------------商户基本信息--------------------------------------------------------

    //@RequiresPermissions("商户管理:银联直连商户管理")
    @GetMapping(value = "/getMchntSvcType")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "mchntCd", value = "商户号", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "操作标识", required = true, dataType = "String")
    })
    public Map getMchntSvcType(@NotBlank(message = "{required}") String mchntCd, @NotBlank(message = "{required}") String optFlag) throws RedpException {
        HashMap<String, Object> result = new HashMap<>();
        if (PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(optFlag)) {
            // 新增，查询正式表
            DirectMchntBaseInfo directBaseInfo = directBaseInfoService.getByMchntCd(mchntCd);
            if (null != directBaseInfo) {
                result.put("mchntSvcTp", directBaseInfo.getMchntSvcTp());
            }
        } else {
            // 修改，需要审核查询临时表，不需要审核查询正式表
            UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
            UpmpPrivilegeCheck privilegeCheck = privilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "银联直连商户管理:修改");
            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                List<BizTmp> baseInfoList = bizTmpService.getBizTmpByMchntCd(mchntCd, "t_b_direct_mchnt_base_info");
                if (null == baseInfoList || baseInfoList.size() <= 0) {
                    log.error("根据id没有找到指定临时表数据！");
                    throw new RedpException("根据id没有找到指定临时表数据！");
                }

                BizTmp tmp = baseInfoList.get(0);
                String bizdata = "";
                if (null != tmp.getBizData1()) {
                    bizdata += tmp.getBizData1();
                }
                if (null != tmp.getBizData2()) {
                    bizdata += tmp.getBizData2();
                }
                if (null != tmp.getBizData3()) {
                    bizdata += tmp.getBizData3();
                }
                DirectMchntBaseInfo directBaseInfo = JSON.parseObject(bizdata, DirectMchntBaseInfo.class);
                if (null != directBaseInfo) {
                    result.put("mchntSvcTp", directBaseInfo.getMchntSvcTp());
                }
            } else {
                // 查询正式表
                DirectMchntBaseInfo directBaseInfo = directBaseInfoService.getByMchntCd(mchntCd);
                if (null != directBaseInfo) {
                    result.put("mchntSvcTp", directBaseInfo.getMchntSvcTp());
                }
            }
        }
        return result;
    }

    //@RequiresPermissions("商户管理:银联直连商户管理")
    @GetMapping(value = "/baseInfo")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "mchntCd", value = "商户号", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "操作标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String")
    })
    public Map baseInfoShow(String mchntCd, @NotBlank(message = "{required}") String optFlag, String instId) throws RedpException {
        HashMap<String, Object> result = new HashMap<>();
        mchntCd = mchntCd == null || mchntCd == "" ? "0" : mchntCd;
        optFlag = optFlag == null ? "" : optFlag;
        instId = instId == null ? "" : instId;
        DirectMchntBaseInfo entity = new DirectMchntBaseInfo();
        if (PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(optFlag)) {
            //由于这几个字段是必填，这里预先赋值否则录入界面因为隐藏输入域而无法通过非空校验
            entity.setMchntCd("00000000");
            entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_NOTCOMMIT.getType());
            entity.setMchntStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
            entity.setCupsReportStatus("00");
            entity.setCreateTime(DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"));
            UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
            entity.setOprId(user.getId());
            entity.setInstId(instId);
        } else {
            // 修改，注销，停用，启用，详情，审批
            if (Common.isBlank(mchntCd)) {
                log.error("请求参数(mchntCd)异常!");
                throw new RedpException("请求参数(mchntCd)异常！");
            }
            // 除审核外其他操作查询正式表
            entity = directBaseInfoService.getByMchntCd(mchntCd);
            // 审核：获取临时表数据并转换成实体对象
            if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(optFlag)) {
                BizTmp tmp = bizTmpService.getById(entity.getId());
                if (Common.isBlank(tmp)) {
                    log.error("根据id没有找到指定临时表数据！");
                    throw new RedpException("根据id没有找到指定临时表数据！");
                }
                String bizdata = "";
                if (null != tmp.getBizData1()) {
                    bizdata += tmp.getBizData1();
                }
                if (null != tmp.getBizData2()) {
                    bizdata += tmp.getBizData2();
                }
                if (null != tmp.getBizData3()) {
                    bizdata += tmp.getBizData3();
                }
                entity = JSON.parseObject(bizdata, DirectMchntBaseInfo.class);
            }

            if (Common.isBlank(entity)) {
                log.error("根据id没有找到指定数据！");
                throw new RedpException("根据id没有找到指定数据！");
            }
        }

        // 处理数据 去除开头08长度位 保存时补充08长度位
        // 收单机构代码
        if (StringUtils.isNotBlank(entity.getAcqInsIdCd()) && entity.getAcqInsIdCd().indexOf("08") == 0) {
            entity.setAcqInsIdCd(entity.getAcqInsIdCd().substring(2));
        }
        // 受理机构代码
        if (StringUtils.isNotBlank(entity.getAcptInsIdCd()) && entity.getAcptInsIdCd().indexOf("08") == 0) {
            entity.setAcptInsIdCd(entity.getAcptInsIdCd().substring(2));
        }
        // 收单接入机构代码
        if (StringUtils.isNotBlank(entity.getAcqAccessInsIdCd()) && entity.getAcqAccessInsIdCd().indexOf("08") == 0) {
            entity.setAcqAccessInsIdCd(entity.getAcqAccessInsIdCd().substring(2));
        }

        RegionInfo gbRegion = regionInfoService.findOneByCode(entity.getGbRegionCd(), BusinessContainer.data_sta_01);
        if (Common.isNotBlank(gbRegion)) {
            result.put("gbRegionName", gbRegion.getRegionName());
        }
        String acqRegionName = areaInfoService.findNameByCode(entity.getAcqRegionCd());
        result.put("acqRegionName", acqRegionName);
        String regionName = areaInfoService.findNameByCode(entity.getRegionCd());
        result.put("regionName", regionName);

        IndustryInfo industryInfo = industryInfoService.findAllindusByInTp(entity.getMchntTp());
        result.put("mchntTpName", industryInfo == null ? "" : industryInfo.getIndustryName());
        MerGrpInfo merGrpInfo = merGrpInfoService.findByGrpNo(entity.getMchntGrp());
        result.put("mchntGrpName", merGrpInfo == null ? "" : merGrpInfo.getGrpDesc());
        // 所属平台机构代码;一般情况下等于收单接入机构代码
        entity.setPlatInsIdCd(entity.getAcqAccessInsIdCd());
        //
        result.put("optFlag", optFlag);
        result.put("entity", entity);
        return result;
    }

    //@RequiresPermissions("商户管理:银联直连商户管理")
    @PostMapping(value = "/baseInfoEdit")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "操作标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String")
    })
    @Transactional(value = "transactionManager")
    public OperationResult baseInfoEditSave(@Valid DirectMchntBaseInfo entity, @NotBlank(message = "{required}") String optFlag) throws RedpException {
        String menuId;
        if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(optFlag)) {
            menuId = String.valueOf(chkMenuId);
        } else {
            menuId = String.valueOf(oprMenuId);
        }
        // 处理数据 补充08长度位
        // 收单机构代码
        if (StringUtils.isNotBlank(entity.getAcqInsIdCd())) {
            entity.setAcqInsIdCd("08" + entity.getAcqInsIdCd());
        }
        // 受理机构代码
        if (StringUtils.isNotBlank(entity.getAcptInsIdCd())) {
            entity.setAcptInsIdCd("08" + entity.getAcptInsIdCd());
        }
        // 收单接入机构代码
        if (StringUtils.isNotBlank(entity.getAcqAccessInsIdCd())) {
            entity.setAcqAccessInsIdCd("08" + entity.getAcqAccessInsIdCd());
        }
        // 所属平台机构代码;一般情况下等于收单接入机构代码
        entity.setPlatInsIdCd(entity.getAcqAccessInsIdCd());

        return directBaseInfoService.saveData(menuId, oprMenuName, entity, webNextUrl, optFlag);
    }

    @PostMapping(value = "/gridExportAll")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "fileName", value = "文件名", required = true, dataType = "String")
    })
    public void gridExportAll(QueryRequest queryRequest, String fileName, DirectMchntBaseInfo entity, HttpServletRequest request, HttpServletResponse response) throws RedpException, IOException {
        InputStream inputStream = null;
        try {
            String filename = fileName;
            filename = new String(filename.getBytes("GBK"), "ISO-8859-1");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            // 使用导出模板
            fileName = "直联商户统一注册格式.xlsx";
            String positation = request.getSession().getServletContext().getRealPath("/") + File.separator + "template" + File.separator;
            String path = positation + File.separator + fileName;
            inputStream = new FileInputStream(path);
            XSSFWorkbook wb = new XSSFWorkbook(inputStream);//创建Excel工作簿对象
            XSSFSheet sheet = wb.getSheetAt(0);// 获取Excel工作表对象
            // 查询数据
            IPage<Map<String, Object>> exportDatas = directBaseInfoService.findExportDataByPage(queryRequest, entity);
            List<Map<String, Object>> rows = exportDatas.getRecords();
            OutputStream os = response.getOutputStream();
            // 组装excel
            if (rows != null) {
                for (int i = 0; i < rows.size(); i++) {
                    XSSFRow hssfRow = sheet.createRow(i + 1);
                    Map<String, Object> row = rows.get(i);
                    String[] tableColumnArr = getTableColumn();
                    for (int idx = 0; idx < tableColumnArr.length; idx++) {
                        String column = tableColumnArr[idx].toUpperCase();
                        XSSFCell cell = hssfRow.createCell(idx);
                        if (idx == 0) {
                            cell.setCellValue("I");
                            continue;
                        }
                        if (null == row.get(column)) {
                            cell.setCellValue("");
                        } else {
                            cell.setCellValue(row.get(column).toString());
                        }
                    }
                }
            }
            wb.write(os);
            IOUtils.closeQuietly(os);
        } catch (Exception e) {
            log.error("直联商户导出异常", e);
            throw new RedpException("直联商户导出异常：" + e.getMessage());
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }

    private String[] getTableColumn() {
        return new String[]{
                "oper_in",
                "mchnt_cd",
                "mchnt_svc_tp",
                "cup_branch_ins_id_cd",
                "mchnt_cn_nm",
                "mchnt_cn_abbr",
                "acq_ins_id_cd",
                "acpt_ins_id_cd",
                "plat_ins_id_cd",
                "acq_access_ins_id_cd",
                "cntry_cd",
                "gb_region_cd",
                "acq_region_cd",
                "mchnt_tp",
                "region_cd",
                "real_mchnt_tp",
                "mchnt_grp",
                "mchnt_st",
                "industry_tp",
                "card_accpt_nm_addr",
                "mchnt_en_nm",
                "mchnt_en_abbr",
                "resv_fld2",
                "conn_md",
                "mis_mchnt_in",
                "mchnt_acpt_curr_bmp",
                "mchnt_dft_curr_cd",
                "lic_no",
                "lic_expire_dt",
                "iss_organ",
                "reg_addr",
                "reve_reg_cd",
                "etps_attr",
                "corp_id",
                "artif_certif_tp",
                "artif_certif_id",
                "artif_nm",
                "contact_person_nm",
                "comm_addr",
                "zip_cd",
                "phone",
                "mobile",
                "email_addr",
                "fax_no",
                "cfo_nm",
                "maintn_company_tp",
                "reg_cap",
                "reg_captial_curr_cd",
                "buss_range",
                "buss_addr",
                "sign_in",
                "enotes_in",
                "settle_ins_tp",
                "acct_ins_id_cd",
                "mchnt_settle_md",
                "pack_mchnt_cd",
                "cycle_settle_tp",
                "prepay_return_tp",
                "mchnt_settle_in",
                "bank_nm1",
                "bank_settle_no1",
                "mchnt_settle_bank_cd",
                "acct_curr_cd1",
                "acct_nm1",
                "acct_no1",
                "spec_settle_in",
                "iss_ins_id_cd",
                "spec_disc_tp",
                "spec_disc_lvl",
                "allot_algo",
                "mchnt_disc_det_index",
                "mcmgm_allot_item_index",
                "allot_role",
                "allot_ins_id_cd1",
                "allot_ins_id_cd2",
                "allot_ins_id_cd3",
                "allot_ins_id_cd4",
                "allot_ins_id_cd5",
                "mchnt_class",
                "rpt_gen_in_bmp",
                "ins_resv7",
                "bank_settle_seq",
                "inday_settle_in",
                "addn_inf",
                "iferr_acq_pay_flag",
                "mchnt_prio_in",
                "inday_cycle_msg_no",
                "inday_cycle_buss_tp",
                "endday_cycle_msg_no",
                "endday_cycle_buss_tp",
                "any_cycle_dbit_msg_no",
                "any_cycle_dbit_buss_tp",
                "mchnt_attr_bmp",
                "fee_settle_ins_tp",
                "mchnt_fee_bank_nm",
                "mchnt_fee_acct_bank_cd",
                "mchnt_fee_acct",
                "mchnt_fee_acct_nm",
                "mchnt_fee_settle_bank_cd",
                "mchnt_fee_acct_ins_id_cd",
                "sp_ins_id_cd",
                "industry_ins_id_cd",
                "mchnt_buss_proc_tp",
                "trust_app_tp",
                "late_fee_calc_in",
                "late_fee_calc_md",
                "late_fee_usr_tp",
                "max_bill_print_num",
                "fix_at",
                "late_fee_lower_limit",
                "late_fee_higher_limit",
                "late_fee_base_rt",
                "late_fee_over_year_rt",
                "mchnt_settle_attr",
                "entrust_relation_in",
                "add_act_entrust_in",
                "tax_tp",
                "settle_tre_bank_no",
                "pwd_enc_tp",
                "pwd_enc_index",
                "chnl_mchnt_cd",
                "spec_charge_in",
                "allot_in",
                "svc_net_url",
                "mchnt_web_site_nm",
                "buss_tp",
                "prod_func",
                "ebuss_tp",
                "prod_func_desc",
                "single_at_limit",
                "single_at_limit_desc",
                "single_card_day_at_limit",
                "single_card_day_at_limit_desc",
                "buss_cont1",
                "buss_cont1_tel",
                "buss_cont1_cell",
                "buss_cont1_email",
                "buss_cont2",
                "buss_cont2_tel",
                "buss_cont2_cell",
                "buss_cont2_email",
                "cup_branch_resv10",
                "cup_branch_resv9",
                "cycle_mchnt_in",
                "mchnt_trans_tp",
                "frn_acq_ins_id_cd",
                "ins_resv8",
                "svc_fee_in",
                "instl_in",
                "call_center_phone",
                "mchnt_lvl",
                "pos_num",
                "casher_num",
                "mchnt_open_dt",
                "constr_quit_dt",
                "trans_chnl",
                "constr_quit_rsn_cd",
                "remark",
                "cup_branch_spec_fld",
                "ins_resv1",
                "ins_resv2",
                "ins_resv3",
                "ins_resv4",
                "ins_resv5",
                "ins_resv6",
                "ins_resv9",
                "ins_resv10",
                "cup_branch_resv1",
                "cup_branch_resv2",
                "cup_branch_resv3",
                "cup_branch_resv4",
                "cup_branch_resv5",
                "cup_branch_resv6",
                "cup_branch_resv7",
                "cup_branch_resv8",
                "cup_hdqrs_resv1",
                "cup_hdqrs_resv2",
                "cup_hdqrs_resv3",
                "cup_hdqrs_resv4",
                "mchnt_neg_act_in",
                "risk_artif_in",
                "risk_mchnt_in",
                "sus_mchnt_in",
                "hdqrs_branch_in",
                "hdqrs_mchnt_cd",
                "recncl_tp",
                "net_mchnt_svc_tp",
                "principal_nm",
                "submchnt_in",
                "svc_ins_nm",
                "cooking",
                "mchnt_icp",
                "traffic_line",
                "direct_acq_settle_in",
                "nm_addr",
                "allot_cd",
                "mcc_appl_rule",
                "master_pwd",
                "mcc_appl_rsn_cd",
                "spec_fee_std_desc",
                "nm_addr2"
        };

        //  "操作标识",
        //  "商户代码",
        //  "商户服务类型",
        //  "所属分公司代码",
        //  "商户法定名称",
        //  "商户经营名称",
        //  "收单机构代码",
        //  "受理机构代码",
        //  "所属平台机构代码",
        //  "收单接入机构代码",
        //  "国家代码",
        //  "行政区划代码",
        //  "受理地区代码",
        //  "交易商户类型",
        //  "清算地区代码",
        //  "真实商户类型",
        //  "商户组别",
        //  "商户状态",
        //  "所属行业类型",
        //  "受卡方名称地址",
        //  "商户英文名称",
        //  "商户英文简称",
        //  "交易特殊控制",
        //  "联接方式",
        //  "是否MIS商户",
        //  "交易币种",
        //  "默认交易币种",
        //  "营业证明文件号码",
        //  "执照有效期",
        //  "发证机关",
        //  "注册地址",
        //  "税务登记代码",
        //  "企业性质",
        //  "企业代码",
        //  "法人代表证件类型",
        //  "法人代表证件号码",
        //  "法人代表姓名",
        //  "商户联系人",
        //  "商户联系人通讯地址",
        //  "邮编",
        //  "商户联系人电话",
        //  "移动电话",
        //  "电子邮件",
        //  "传真",
        //  "财务联系人",
        //  "终端维护公司",
        //  "注册资本",
        //  "注册资本币种",
        //  "经营范围",
        //  "营业地址",
        //  "签约标志",
        //  "电子票据业务标志",
        //  "资金入账方式",
        //  "结算行机构代码",
        //  "商户清算模式",
        //  "入账商户代码",
        //  "资金划付周期",
        //  "垫付回补类型",
        //  "直联清算标识",
        //  "商户开户行名称",
        //  "商户开户行行号",
        //  "开户行接收行行号",
        //  "商户账户币种",
        //  "商户账户名称",
        //  "商户账号",
        //  "本金清算类型",
        //  "不清本金发卡机构代码",
        //  "特殊计费类型",
        //  "特殊计费档次",
        //  "发卡银联分润算法",
        //  "商户计费算法",
        //  "收单分润算法",
        //  "分润角色",
        //  "商户服务1",
        //  "商户服务2",
        //  "商户服务3",
        //  "商户服务4",
        //  "商户服务5",
        //  "商户层级",
        //  "报表类型",
        //  "收单收益帐号",
        //  "开户行清算号",
        //  "是否参加日间清算",
        //  "商户清算附言",
        //  "异常时收单垫付标志",
        //  "商户优先标志",
        //  "日间贷记业务类型号",
        //  "小额业务种类_日间场次",
        //  "日终贷记业务类型号",
        //  "小额业务种类_日终场次",
        //  "支持的借记业务类型号",
        //  "支持的借记业务种类",
        //  "商户属性位图",
        //  "费用入账方式",
        //  "商户费用开户行名称",
        //  "商户费用账号开户行行号",
        //  "商户费用账号",
        //  "商户费用账户名称",
        //  "商户费用开户行清算号",
        //  "商户费用结算行机构代码",
        //  "sp机构代码",
        //  "行业机构代码",
        //  "商户业务处理方式",
        //  "托管应用类型",
        //  "滞纳金计算标志",
        //  "滞纳金计算模式",
        //  "滞纳金用户类型",
        //  "最大票据打印次数",
        //  "固定金额",
        //  "最低限额",
        //  "最高限额",
        //  "基准利率",
        //  "跨年利率",
        //  "商户结算性质",
        //  "委托关系是否允许覆盖",
        //  "增加主动委托关系标志",
        //  "税务类别",
        //  "清算国库行号/征收机关代码",
        //  "密码加密类型",
        //  "密码加密索引",
        //  "渠道接入商代码",
        //  "代收授权标志",
        //  "新业务规则启用标志",
        //  "商户网址",
        //  "商户网站名称",
        //  "业务类型",
        //  "产品功能套餐",
        //  "卡种",
        //  "共享证书主商户号",
        //  "单笔限额",
        //  "单笔限额说明",
        //  "单卡单日累计限额",
        //  "单卡单日累计限额说明",
        //  "业务联系人",
        //  "业务联系人固话",
        //  "业务联系人移动电话",
        //  "业务联系人邮箱",
        //  "技术联系人",
        //  "技术联系人固话",
        //  "技术联系人移动电话",
        //  "技术联系人邮箱",
        //  "语音业务类型支持位图",
        //  "语音支付合作机构",
        //  "MAC校验和交易加密标志",
        //  "商户交易种类",
        //  "外卡收单行代码",
        //  "第三方服务机构代码",
        //  "是否向商户收取服务费",
        //  "是否开展分期付款",
        //  "客服电话",
        //  "商户等级",
        //  "POS台数",
        //  "收银台数量",
        //  "开业经营日期",
        //  "强制退出时间",
        //  "商户交易渠道",
        //  "强制退出原因码",
        //  "备注",
        //  "分公司特殊字段",
        //  "机构保留字段1",
        //  "机构保留字段2",
        //  "机构保留字段3",
        //  "机构保留字段4",
        //  "机构保留字段5",
        //  "机构保留字段6",
        //  "机构保留字段9",
        //  "机构保留字段10",
        //  "分公司保留字段1",
        //  "分公司保留字段2",
        //  "分公司保留字段3",
        //  "分公司保留字段4",
        //  "分公司保留字段5",
        //  "分公司保留字段6",
        //  "分公司保留字段7",
        //  "分公司保留字段8",
        //  "总公司保留字段1",
        //  "总公司保留字段2",
        //  "总公司保留字段3",
        //  "总公司保留字段4",
        //  "商户是否有不良记录",
        //  "法人是否列入风险商户法人名单",
        //  "商户是否列入风险商户名单",
        //  "商户是否列入可疑商户名单",
        //  "总分店标志",
        //  "总店商户代码",
        //  "商户拓展方式",
        //  "营业证明文件类型",
        //  "收单外包服务机构",
        //  "网络商户类型",
        //  "ICP许可证编号",
        //  "商户开票开户银行名称",
        //  "商户开票账号",
        //  "商户开票账户名称",
        //  "是否申请非标准价格",
        //  "商户现场注册标识码",
        //  "贷记卡发卡银联分润算法",
        //  "是否开通免密免签",
        //  "品牌",
        //  "业务扩展预留字段1",
        //  "业务扩展预留字段2",
        //  "业务扩展预留字段3"
    }
    // -----------------------------------------------签约信息-----------------------------------------------------------

    //@RequiresPermissions("商户管理:银联直连商户管理")
    @GetMapping(value = "/signInfo")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "mchntCd", value = "商户号", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "操作标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String")
    })
    public Map signInfoShow(String mchntCd, @NotBlank(message = "{required}") String optFlag, String instId) throws RedpException {
        java.util.Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        mchntCd = mchntCd == null || mchntCd == "" ? "0" : mchntCd;
        optFlag = optFlag == null ? "" : optFlag;
        instId = instId == null ? "" : instId;
        if (Common.isBlank(optFlag)) {
            log.error("请求参数(optFlag)异常!");
            throw new RedpException("请求参数异常！");
        }

        DirectMchntSignInfo entity = new DirectMchntSignInfo();
        if (PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(optFlag)) {
            //由于这几个字段是必填，这里预先赋值否则录入界面因为隐藏输入域而无法通过非空校验
            entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_NOTCOMMIT.getType());
            entity.setMchntSignStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
            entity.setCreateTime(DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"));
            UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
            entity.setOprId(user.getId());
            entity.setInstId(instId);
        } else {
            // 修改，注销，停用，启用，详情，审批
            if (Common.isBlank(mchntCd)) {
                log.error("请求参数(mchntCd)异常!");
                throw new RedpException("请求参数(mchntCd)异常！");
            }
            // 除审核、修改外其他操作查询正式表
            entity = directSignInfoService.getByMchntCd(mchntCd);
            // 审核：获取临时表数据并转换成实体对象
            if ((PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(optFlag) ||
                    PageOptFlagEnum.OPT_FLAG_UPDATE.getType().equals(optFlag)) && null != entity) {
                BizTmp tmp = bizTmpService.getById(entity.getId());
                if (Common.isNotBlank(tmp)) {
                    String bizdata = "";
                    if (null != tmp.getBizData1()) {
                        bizdata += tmp.getBizData1();
                    }
                    if (null != tmp.getBizData2()) {
                        bizdata += tmp.getBizData2();
                    }
                    if (null != tmp.getBizData3()) {
                        bizdata += tmp.getBizData3();
                    }
                    entity = JSON.parseObject(bizdata, DirectMchntSignInfo.class);
                }
            }

            if (Common.isBlank(entity)) {
                DirectMchntBaseInfo directBaseInfo = directBaseInfoService.getByMchntCd(mchntCd);
                if (directBaseInfo.getAuditStatus().equals(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_NOTCOMMIT.getType())) {
                    // 处理：新增途中关闭界面，导致数据不存在。改变为新增操作
                    entity = new DirectMchntSignInfo();
                    entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_NOTCOMMIT.getType());
                    entity.setMchntSignStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
                    entity.setCreateTime(DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"));
                    UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
                    entity.setOprId(user.getId());
                    entity.setInstId(instId);
                } else {
                    log.error("根据id没有找到指定数据！");
                    throw new RedpException("根据id没有找到指定数据！");
                }
            }
        }
        //
        result.put("optFlag", optFlag);
        result.put("mchntCd", mchntCd);
        result.put("clazz", DirectMchntSignInfo.class.getName());
        result.put("entity", entity);
        result.put("entity", entity);
        return result;
    }

    //@RequiresPermissions("商户管理:银联直连商户管理")
    @PostMapping(value = "/signInfoEdit")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "主键", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "操作标识", required = true, dataType = "String")
    })
    public OperationResult signInfoEditSave(@ModelAttribute("merSignInfo") DirectMchntSignInfo entity, HttpServletRequest request) throws RedpException {
        String optFlag = request.getParameter("optFlag");
        String menuId;
        if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(optFlag)) {
            menuId = String.valueOf(chkMenuId);
        } else {
            menuId = String.valueOf(oprMenuId);
        }
        return directSignInfoService.saveData(menuId, oprMenuName, entity, request, webNextUrl, optFlag);
    }

    // -----------------------------------------------影像信息-----------------------------------------------------------

    //@RequiresPermissions("商户管理:银联直连商户管理")
    @GetMapping(value = "/signFileInfo")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "mchntCd", value = "商户号", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "操作标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "lastAuditStatus", value = "状态", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String")
    })
    public Map signFileInfoShow(String mchntCd, @NotBlank(message = "{required}") String optFlag, String instId, String lastAuditStatus) throws RedpException {
        java.util.Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        mchntCd = mchntCd == null || mchntCd == "" ? "" : mchntCd;
        optFlag = optFlag == null ? "" : optFlag;
        instId = instId == null ? "" : instId;
        lastAuditStatus = lastAuditStatus == null ? "" : lastAuditStatus;
        if (Common.isBlank(optFlag)) {
            log.error("请求参数(optFlag)异常!");
            throw new RedpException("请求参数异常！");
        }
        DirectMchntImageManageVO vo = new DirectMchntImageManageVO();
        vo.setOptFlag(optFlag);
        vo.setInstId(instId);
        if (PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(optFlag)) {
            //由于这几个字段是必填，这里预先赋值否则录入界面因为隐藏输入域而无法通过非空校验
        } else {
            List<UpmpBMchntImageInfo> bMchntImageInfoList = new ArrayList<>();
            // 修改，注销，停用，启用，详情，审批
            if (Common.isBlank(mchntCd)) {
                log.error("请求参数(mchntCd)异常!");
                throw new RedpException("请求参数(mchntCd)异常！");
            }
            // 查询正式表数据
            bMchntImageInfoList = directMchntImageInfoService.getBMchntImageInfoByMchntNo(mchntCd);
            // 审核：获取临时表数据并转换成实体对象
            if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(optFlag) ||
                    PageOptFlagEnum.OPT_FLAG_UPDATE.getType().equals(optFlag)) {
                List<BizTmp> bizTmps = bizTmpService.getBizTmpByMchntCd(mchntCd, "t_b_mchnt_image_info");
                if (null != bizTmps && bizTmps.size() > 0) {
                    for (BizTmp bizTmp : bizTmps) {
                        String bizdata = "";
                        if (null != bizTmp.getBizData1()) {
                            bizdata += bizTmp.getBizData1();
                        }
                        if (null != bizTmp.getBizData2()) {
                            bizdata += bizTmp.getBizData2();
                        }
                        if (null != bizTmp.getBizData3()) {
                            bizdata += bizTmp.getBizData3();
                        }
                        UpmpBMchntImageInfo bMchntImageInfo = JSON.parseObject(bizdata, UpmpBMchntImageInfo.class);
                        bMchntImageInfo.setImagePath(bMchntImageInfo.getImageRemotePath());
                        bMchntImageInfoList.add(bMchntImageInfo);
                    }
                }
            }
            if (null == bMchntImageInfoList || bMchntImageInfoList.size() <= 0) {
                DirectMchntBaseInfo directBaseInfo = directBaseInfoService.getByMchntCd(mchntCd);
                if (directBaseInfo.getAuditStatus().equals(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_NOTCOMMIT.getType())) {
                    // 处理：新增途中关闭界面，导致数据不存在。改变为新增操作

                } else {
                    log.error("根据mchntCd没有找到指定数据！");
                    throw new RedpException("根据mchntCd没有找到指定数据！");
                }
            }
            // 对象转换
            directMchntImageInfoService.transformDirectMchntImageManageVO(bMchntImageInfoList, vo);
            // 赋值商户签约协议号
            DirectMchntSignInfo DirectMchntSignInfo = directSignInfoService.getByMchntCd(mchntCd);
            if (null != DirectMchntSignInfo) {
                vo.setMchntSignId(DirectMchntSignInfo.getMchntSignId());
                vo.setInstId(instId);
            }
        }
        if (Common.isNotBlank(vo.getBusinessLicense()) && Common.isNotBlank(vo.getBusinessLicense().getImageLocalPath())) {
            //经营执照
            vo.getBusinessLicense().setImageLocalPath(Base64.encodeToString(vo.getBusinessLicense().getImageLocalPath().getBytes()));
        }
        if (Common.isNotBlank(vo.getFrontCert()) && Common.isNotBlank(vo.getFrontCert().getImageLocalPath())) {
            //负责人身份证(人像面)
            vo.getFrontCert().setImageLocalPath(Base64.encodeToString(vo.getFrontCert().getImageLocalPath().getBytes()));
        }

        if (Common.isNotBlank(vo.getReverseCert()) && Common.isNotBlank(vo.getReverseCert().getImageLocalPath())) {
            //负责人身份证(国徽面)
            vo.getReverseCert().setImageLocalPath(Base64.encodeToString(vo.getReverseCert().getImageLocalPath().getBytes()));
        }

        if (Common.isNotBlank(vo.getHoldingCert()) && Common.isNotBlank(vo.getHoldingCert().getImageLocalPath())) {
            //负责人手持身份证
            vo.getHoldingCert().setImageLocalPath(Base64.encodeToString(vo.getHoldingCert().getImageLocalPath().getBytes()));
        }

        if (Common.isNotBlank(vo.getShopFront()) && Common.isNotBlank(vo.getShopFront().getImageLocalPath())) {
            //商户门头照
            vo.getShopFront().setImageLocalPath(Base64.encodeToString(vo.getShopFront().getImageLocalPath().getBytes()));
        }

        //经营场所照 list
        List<UpmpBMchntImageInfo> premisesList = vo.getPremisesList();
        if (premisesList != null && premisesList.size() > 0) {
            for (UpmpBMchntImageInfo bMchntImageInfo : premisesList) {
                if (Common.isNotBlank(bMchntImageInfo.getImageLocalPath())) {
                    bMchntImageInfo.setImageLocalPath(Base64.encodeToString(bMchntImageInfo.getImageLocalPath().getBytes()));
                }
            }
        }

        //人行征信查询授权书 list
        List<UpmpBMchntImageInfo> creditAuthList = vo.getCreditAuthList();
        if (creditAuthList != null && creditAuthList.size() > 0) {
            for (UpmpBMchntImageInfo bMchntImageInfo : creditAuthList) {
                if (Common.isNotBlank(bMchntImageInfo.getImageLocalPath())) {
                    bMchntImageInfo.setImageLocalPath(Base64.encodeToString(bMchntImageInfo.getImageLocalPath().getBytes()));
                }
            }
        }


        //征信报告 list
        List<UpmpBMchntImageInfo> creditReportList = vo.getCreditReportList();
        if (creditReportList != null && creditReportList.size() > 0) {
            for (UpmpBMchntImageInfo bMchntImageInfo : creditReportList) {
                if (Common.isNotBlank(bMchntImageInfo.getImageLocalPath())) {
                    bMchntImageInfo.setImageLocalPath(Base64.encodeToString(bMchntImageInfo.getImageLocalPath().getBytes()));
                }
            }
        }


        //身份证联网核查报告 list
        List<UpmpBMchntImageInfo> networkVerifyList = vo.getNetworkVerifyList();
        if (networkVerifyList != null && networkVerifyList.size() > 0) {
            for (UpmpBMchntImageInfo bMchntImageInfo : networkVerifyList) {
                if (Common.isNotBlank(bMchntImageInfo.getImageLocalPath())) {
                    bMchntImageInfo.setImageLocalPath(Base64.encodeToString(bMchntImageInfo.getImageLocalPath().getBytes()));
                }
            }
        }


        //其他电子资料文件 list
        List<UpmpBMchntImageInfo> otherFileList = vo.getOtherFileList();
        if (otherFileList != null && otherFileList.size() > 0) {
            for (UpmpBMchntImageInfo bMchntImageInfo : otherFileList) {
                if (Common.isNotBlank(bMchntImageInfo.getImageLocalPath())) {
                    bMchntImageInfo.setImageLocalPath(Base64.encodeToString(bMchntImageInfo.getImageLocalPath().getBytes()));
                }
            }
        }

        result.put("optFlag", optFlag);
        result.put("mchntCd", mchntCd);
        result.put("lastAuditStatus", lastAuditStatus);
        result.put("clazz", DirectMchntImageManageVO.class.getName());
        result.put("entity", vo);

        return result;
    }

    //@RequiresPermissions("商户管理:银联直连商户管理")
    @PostMapping(value = "/signFileInfoEdit")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "操作标识", required = true, dataType = "String")
    })
    public OperationResult signFileInfoEditSave(@RequestBody DirectMchntImageManageVO entity, HttpServletRequest request) throws RedpException {
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        CommonUtils.validateUserInst(entity.getInstId(), user);

        String optFlag = request.getParameter("optFlag");
        String menuId;
        if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(optFlag)) {
            menuId = String.valueOf(chkMenuId);
        } else {
            menuId = String.valueOf(oprMenuId);
        }
        if (Common.isNotBlank(entity.getBusinessLicense()) && Common.isNotBlank(entity.getBusinessLicense().getImageLocalPath())) {
            //经营执照
            entity.getBusinessLicense().setImageLocalPath(Base64.decodeToString(entity.getBusinessLicense().getImageLocalPath()));
        }
        if (Common.isNotBlank(entity.getFrontCert()) && Common.isNotBlank(entity.getFrontCert().getImageLocalPath())) {
            //负责人身份证(人像面)
            entity.getFrontCert().setImageLocalPath(Base64.decodeToString(entity.getFrontCert().getImageLocalPath()));
        }

        if (Common.isNotBlank(entity.getReverseCert()) && Common.isNotBlank(entity.getReverseCert().getImageLocalPath())) {
            //负责人身份证(国徽面)
            entity.getReverseCert().setImageLocalPath(Base64.decodeToString(entity.getReverseCert().getImageLocalPath()));
        }

        if (Common.isNotBlank(entity.getHoldingCert()) && Common.isNotBlank(entity.getHoldingCert().getImageLocalPath())) {
            //负责人手持身份证
            entity.getHoldingCert().setImageLocalPath(Base64.decodeToString(entity.getHoldingCert().getImageLocalPath()));
        }

        if (Common.isNotBlank(entity.getShopFront()) && Common.isNotBlank(entity.getShopFront().getImageLocalPath())) {
            //商户门头照
            entity.getShopFront().setImageLocalPath(Base64.decodeToString(entity.getShopFront().getImageLocalPath()));
        }

        //经营场所照 list
        List<UpmpBMchntImageInfo> premisesList = entity.getPremisesList();
        for (UpmpBMchntImageInfo bMchntImageInfo : premisesList) {
            if (Common.isNotBlank(bMchntImageInfo.getImageLocalPath())) {
                bMchntImageInfo.setImageLocalPath(Base64.decodeToString(bMchntImageInfo.getImageLocalPath()));
            }
        }

        //人行征信查询授权书 list
        List<UpmpBMchntImageInfo> creditAuthList = entity.getCreditAuthList();
        for (UpmpBMchntImageInfo bMchntImageInfo : creditAuthList) {
            if (Common.isNotBlank(bMchntImageInfo.getImageLocalPath())) {
                bMchntImageInfo.setImageLocalPath(Base64.decodeToString(bMchntImageInfo.getImageLocalPath()));
            }
        }

        //征信报告 list
        List<UpmpBMchntImageInfo> creditReportList = entity.getCreditReportList();
        for (UpmpBMchntImageInfo bMchntImageInfo : creditReportList) {
            if (Common.isNotBlank(bMchntImageInfo.getImageLocalPath())) {
                bMchntImageInfo.setImageLocalPath(Base64.decodeToString(bMchntImageInfo.getImageLocalPath()));
            }
        }

        //身份证联网核查报告 list
        List<UpmpBMchntImageInfo> networkVerifyList = entity.getNetworkVerifyList();
        for (UpmpBMchntImageInfo bMchntImageInfo : networkVerifyList) {
            if (Common.isNotBlank(bMchntImageInfo.getImageLocalPath())) {
                bMchntImageInfo.setImageLocalPath(Base64.decodeToString(bMchntImageInfo.getImageLocalPath()));
            }
        }

        //其他电子资料文件 list
        List<UpmpBMchntImageInfo> otherFileList = entity.getOtherFileList();
        for (UpmpBMchntImageInfo bMchntImageInfo : otherFileList) {
            if (Common.isNotBlank(bMchntImageInfo.getImageLocalPath())) {
                bMchntImageInfo.setImageLocalPath(Base64.decodeToString(bMchntImageInfo.getImageLocalPath()));
            }
        }

        return directMchntImageInfoService.saveData(menuId, oprMenuName, entity, request, webNextUrl, entity.getOptFlag());
    }

    // -----------------------------------------------清算信息-----------------------------------------------------------

    //@RequiresPermissions("商户管理:银联直连商户管理")
    @GetMapping(value = "/clearInfo")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "mchntCd", value = "商户号", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "操作标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String")
    })
    public Map clearInfoShow(String mchntCd, @NotBlank(message = "{required}") String optFlag, String instId) throws RedpException {
        java.util.Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        mchntCd = mchntCd == null || mchntCd == "" ? "" : mchntCd;
        optFlag = optFlag == null ? "" : optFlag;
        instId = instId == null ? "" : instId;
        if (Common.isBlank(optFlag)) {
            log.error("请求参数(optFlag)异常!");
            throw new RedpException("请求参数异常！");
        }

        DirectMchntClearInfo entity = new DirectMchntClearInfo();
        if (PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(optFlag)) {
            entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_NOTCOMMIT.getType());
            entity.setMchntClearStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
            entity.setCreateTime(DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"));
            UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
            entity.setOprId(user.getId());
            entity.setInstId(instId);
        } else {
            // 修改，注销，停用，启用，详情，审批
            if (Common.isBlank(mchntCd)) {
                log.error("请求参数(mchntCd)异常!");
                throw new RedpException("请求参数(mchntCd)异常！");
            }
            // 除审核、修改外其他操作查询正式表
            entity = directClearInfoService.getByMchntCd(mchntCd);
            // 审核：获取临时表数据并转换成实体对象
            if ((PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(optFlag) ||
                    PageOptFlagEnum.OPT_FLAG_UPDATE.getType().equals(optFlag)) && null != entity) {
                BizTmp tmp = bizTmpService.getById(entity.getId());
                if (Common.isNotBlank(tmp)) {
                    String bizdata = "";
                    if (null != tmp.getBizData1()) {
                        bizdata += tmp.getBizData1();
                    }
                    if (null != tmp.getBizData2()) {
                        bizdata += tmp.getBizData2();
                    }
                    if (null != tmp.getBizData3()) {
                        bizdata += tmp.getBizData3();
                    }
                    entity = JSON.parseObject(bizdata, DirectMchntClearInfo.class);
                }
            }

            if (Common.isBlank(entity)) {
                DirectMchntBaseInfo directBaseInfo = directBaseInfoService.getByMchntCd(mchntCd);
                if (directBaseInfo.getAuditStatus().equals(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_NOTCOMMIT.getType())) {
                    // 处理：新增途中关闭界面，导致数据不存在。改变为新增操作
                    entity = new DirectMchntClearInfo();
                    entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_NOTCOMMIT.getType());
                    entity.setMchntClearStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
                    entity.setCreateTime(DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"));
                    UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
                    entity.setOprId(user.getId());
                } else {
                    log.error("根据id没有找到指定数据！");
                    throw new RedpException("根据id没有找到指定数据！");
                }
            }
        }

        result.put("entity", entity);
        result.put("mchntCd", mchntCd);
        result.put("clazz", DirectMchntClearInfo.class.getName());
        result.put("optFlag", optFlag);
        return result;
    }

    //@RequiresPermissions("商户管理:银联直连商户管理")
    @PostMapping(value = "/clearInfoEdit")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "主键", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "操作标识", required = true, dataType = "String")
    })
    public OperationResult clearInfoEditSave(@ModelAttribute("merSignInfo") DirectMchntClearInfo entity, HttpServletRequest request) throws RedpException {
        String optFlag = request.getParameter("optFlag");
        String menuId;
        if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(optFlag)) {
            menuId = String.valueOf(chkMenuId);
        } else {
            menuId = String.valueOf(oprMenuId);
        }
        return directClearInfoService.saveData(menuId, oprMenuName, entity, request, webNextUrl, optFlag);
    }

    // -----------------------------------------------业务信息-----------------------------------------------------------

    //@RequiresPermissions("商户管理:银联直连商户管理")
    @GetMapping(value = "/bizInfo")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "mchntCd", value = "商户号", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "操作标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String")
    })
    public Map bizInfoShow(String mchntCd, @NotBlank(message = "{required}") String optFlag, String instId) throws RedpException {
        java.util.Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        mchntCd = mchntCd == null || mchntCd == "" ? "" : mchntCd;
        optFlag = optFlag == null ? "" : optFlag;
        instId = instId == null ? "" : instId;
        if (Common.isBlank(optFlag)) {
            log.error("请求参数(optFlag)异常!");
            throw new RedpException("请求参数异常！");
        }
        DirectMchntBizInfo entity = new DirectMchntBizInfo();
        if (PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(optFlag)) {
            entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_NOTCOMMIT.getType());
            entity.setMchntBizStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
            entity.setCreateTime(DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"));
            UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
            entity.setOprId(user.getId());
            entity.setInstId(instId);
        } else {
            // 修改，注销，停用，启用，详情，审批
            if (Common.isBlank(mchntCd)) {
                log.error("请求参数(mchntCd)异常!");
                throw new RedpException("请求参数(mchntCd)异常！");
            }
            // 除审核、修改外其他操作查询正式表
            entity = directMchntBizInfoService.getByMchntCd(mchntCd);
            // 审核：获取临时表数据并转换成实体对象
            if ((PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(optFlag) ||
                    PageOptFlagEnum.OPT_FLAG_UPDATE.getType().equals(optFlag)) && null != entity) {
                BizTmp tmp = bizTmpService.getById(entity.getId());
                if (Common.isNotBlank(tmp)) {
                    String bizdata = "";
                    if (null != tmp.getBizData1()) {
                        bizdata += tmp.getBizData1();
                    }
                    if (null != tmp.getBizData2()) {
                        bizdata += tmp.getBizData2();
                    }
                    if (null != tmp.getBizData3()) {
                        bizdata += tmp.getBizData3();
                    }
                    entity = JSON.parseObject(bizdata, DirectMchntBizInfo.class);
                }
            }

            if (Common.isBlank(entity)) {
                DirectMchntBaseInfo directBaseInfo = directBaseInfoService.getByMchntCd(mchntCd);
                if (directBaseInfo.getAuditStatus().equals(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_NOTCOMMIT.getType())) {
                    // 处理：新增途中关闭界面，导致数据不存在。改变为新增操作
                    entity = new DirectMchntBizInfo();
                    entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_NOTCOMMIT.getType());
                    entity.setMchntBizStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
                    entity.setCreateTime(DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"));
                    UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
                    entity.setOprId(user.getId());
                } else {
                    log.error("根据id没有找到指定数据！");
                    throw new RedpException("根据id没有找到指定数据！");
                }
            }
        }

        result.put("entity", entity);
        result.put("mchntCd", mchntCd);
        result.put("clazz", DirectMchntBizInfo.class.getName());
        result.put("optFlag", optFlag);
        return result;
    }

    //@RequiresPermissions("商户管理:银联直连商户管理")
    @PostMapping(value = "/bizInfoEdit")

    public OperationResult bizInfoEditSave(@ModelAttribute("merSignInfo") DirectMchntBizInfo entity, HttpServletRequest request) throws RedpException {
        String optFlag = request.getParameter("optFlag");
        String menuId;
        if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(optFlag)) {
            menuId = String.valueOf(chkMenuId);
        } else {
            menuId = String.valueOf(oprMenuId);
        }

        return directMchntBizInfoService.saveData(menuId, oprMenuName, entity, request, webNextUrl, optFlag);
    }

    /**
     * 商户影像下载
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @GetMapping(value = "/zip")
    public void zip(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, RedpException {
        //查询商户影像信息
        String mchntCd = request.getParameter("mchntNo");
        String instId = request.getParameter("instId");
        String type = request.getParameter("type");
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        List<UpmpBMchntImageInfo> bMchntImageInfoList = new ArrayList<>();
        ImageFileUpDownloadRequest req = new ImageFileUpDownloadRequest();
        String queryType = "0";
        if (type.equals(BompQueryTypeEnum.TEMP.getType())) {
            List<BizTmp> bizTmps = bizTmpService.getBizTmpByMchntCd(mchntCd, "t_b_mchnt_image_info");
            if (null != bizTmps && bizTmps.size() > 0) {
                for (BizTmp bizTmp : bizTmps) {
                    String bizdata = "";
                    if (null != bizTmp.getBizData1()) {
                        bizdata += bizTmp.getBizData1();
                    }
                    if (null != bizTmp.getBizData2()) {
                        bizdata += bizTmp.getBizData2();
                    }
                    if (null != bizTmp.getBizData3()) {
                        bizdata += bizTmp.getBizData3();
                    }
                    UpmpBMchntImageInfo bMchntImageInfo = JSON.parseObject(bizdata, UpmpBMchntImageInfo.class);
                    bMchntImageInfo.setImagePath(bMchntImageInfo.getImageRemotePath());
                    bMchntImageInfoList.add(bMchntImageInfo);
                }
            }
            queryType = "0";
        } else {
            bMchntImageInfoList = directMchntImageInfoService.getBMchntImageInfoByMchntNo(mchntCd);
            queryType = "1";
        }


        List<ImageInfoVO> mchntImagList = directBaseInfoService.getmchntImageList(bMchntImageInfoList);

        req.setMchntNo(mchntCd);
        req.setOprType("01");
        req.setImageType("00");
        req.setUserId(user.getId());

        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("商户影像", "UTF-8") + ".zip");
        response.setCharacterEncoding("UTF-8");
        ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
        for (ImageInfoVO imageinfovo : mchntImagList) {

            req.setId(imageinfovo.getId());


            OperationResult operationResult = bMchntBaseInfoService.imageFileUpDownload(instId, req, bompMchntManageService, bMchntBaseInfoService.genMerOrder(user.getInstId()), queryType);

            if (operationResult.getCode().equals("100000")) {
                try {
                    ImageFileUpDownloadResponse imag = (ImageFileUpDownloadResponse) operationResult.getData();
                    byte[] b = java.util.Base64.getDecoder().decode(imag.getImageData());
                    for (int i = 0; i < b.length; ++i) {
                        if (b[i] < 0) {
                            b[i] += 256;
                        }
                    }
                    ByteArrayInputStream in = new ByteArrayInputStream(b);
                    zos.putNextEntry(new ZipEntry(imageinfovo.getName()));
                    int temp = 0;
                    if ((temp = in.read()) != -1) {
                        zos.write(b);
                    }
                    in.close();
                } catch (Exception ex) {
                    log.error("获取图片失败", ex);
                    throw new RedpException("获取图片失败:" + ex.getCause());
                }

            }

        }
        if (null != zos) {
            zos.flush();
            zos.close();
        }

    }
}
